package com.chenzhen.blog.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author hp
 */
public class FtpUtil {

    private FtpUtil() {
    }

    private static FTPClient connect(String host, int port, String username, String password) throws IOException {
        // 创建 ftp 客户端对象
        FTPClient ftp = new FTPClient();
        // 连接 ftp 服务器
        ftp.connect(host, port);
        // 登录
        ftp.login(username, password);

        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return null;
        } else {
            return ftp;
        }
    }

    private static boolean ftpUploadFile(String basePath, String filePath, String filename, InputStream input, FTPClient ftp)
            throws IOException {
        if (ftp == null) {
            return true;
        }
        ftp.setControlEncoding("UTF-8");
        if (!ftp.changeWorkingDirectory(basePath + filePath)) {
            String[] dirs = filePath.split("/");
            String tempPath = basePath;

            for (String dir : dirs) {
                if (null != dir && !"".equals(dir)) {
                    tempPath = tempPath + "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return true;
                        }

                        ftp.changeWorkingDirectory(tempPath);
                    }
                }
            }
        }
        if (haveSameFile(ftp, filename)) {
            System.out.println("目标文件夹中已经存在相同文件！");
        }
        ftp.setFileType(2);
        ftp.enterLocalPassiveMode();
        return !ftp.storeFile(new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), input);
    }

    public static boolean haveSameFile(FTPClient ftpClient, String fileName) throws IOException {
        FTPFile[] fs = ftpClient.listFiles();

        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                return true;
            }
        }

        return false;
    }

    public static boolean uploadFile(String basePath, String filePath, String filename, InputStream input) {
        try {
            FTPClient ftp = connect("47.108.58.155", 21, "root", "rootlyl");

            if (ftpUploadFile(basePath, filePath, filename, input, ftp)) {

                return false;
            }

            ftp.logout();
            ftp.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }
}